package com.sskj.bibi.ui.fragment;


import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.widget.ImageView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.shizhefei.mvc.MVCCoolHelper;
import com.shizhefei.view.coolrefreshview.CoolRefreshView;
import com.shizhefei.view.coolrefreshview.header.MaterialHeader;
import com.sskj.bibi.R;
import com.sskj.bibi.R2;
import com.sskj.bibi.http.HttpConfig;
import com.sskj.bibi.presenter.SlideHangqingFragmentPresenter;
import com.sskj.common.adapter.ItemClickSupport;
import com.sskj.common.adapter.slimadapter.IViewInjector;
import com.sskj.common.adapter.slimadapter.SlimAdapter;
import com.sskj.common.adapter.slimadapter.SlimInjector;
import com.sskj.common.base.App;
import com.sskj.common.box.decoration.DividerLineItemDecoration;
import com.sskj.common.rxbus2.RxBus;
import com.sskj.common.rxbus2.Subscribe;
import com.sskj.common.rxbus2.ThreadMode;
import com.sskj.common.util.DisposUtil;
import com.sskj.common.util.ImageUtil;
import com.sskj.lib.RConfig;
import com.sskj.lib.base.BaseFragment;
import com.sskj.lib.bean.BibiCoinType;
import com.sskj.lib.bean.CoinBean;
import com.sskj.lib.bean.StockCoinBean;
import com.sskj.lib.mvchelper.RefreshDataSource;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

@Route(path = RConfig.BIBI_FRAGMENT_SLIDE)//侧滑
public class SlideHangqingFragment extends BaseFragment<SlideHangqingFragmentPresenter> {
    @BindView(R2.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R2.id.coolRefreshView)
    CoolRefreshView coolRefreshView;

    @Autowired
    String qu;
    private MVCCoolHelper<List<CoinBean>> mvcHelper;
    private SlimAdapter<CoinBean> slimAdapter;
    private HashMap<String, Integer> coinImg;
    private Map<String, Disposable> timeMap = new HashMap<>();

    @Override
    protected int getLayoutId() {
        return R.layout.bibi_fragment_slide_hangqing;
    }

    @Override
    public SlideHangqingFragmentPresenter getPresenter() {
        return new SlideHangqingFragmentPresenter();
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onWebSocketMessage(CoinBean stockSocketBean) {
        Flowable.fromIterable(slimAdapter.getData())
                .filter(item -> item.getCode().equals(stockSocketBean.getCode()))
                .subscribe(item -> {
                    if (Double.valueOf(stockSocketBean.getChange()) >= 0) {
                        stockSocketBean.setGreen(true);
                    } else {
                        stockSocketBean.setGreen(false);
                    }
                    stockSocketBean.setLight(true);
                    slimAdapter.getData().set(slimAdapter.getData().indexOf(item), stockSocketBean);
                    slimAdapter.notifyItemChanged(slimAdapter.getData().indexOf(stockSocketBean), 1);
                    DisposUtil.close(timeMap.get(item.getCode()));
                    Disposable subscribe = Flowable.timer(600, TimeUnit.MILLISECONDS)
                            .subscribeOn(Schedulers.newThread())
                            .observeOn(AndroidSchedulers.mainThread())
                            .subscribe(i -> {
                                stockSocketBean.setLight(false);
                                slimAdapter.notifyItemChanged(slimAdapter.getData().indexOf(stockSocketBean), 1);
                            });
                    timeMap.put(stockSocketBean.getCode(), subscribe);
                });
    }

    @Override
    public void initView() {
        ARouter.getInstance().inject(this);
        RxBus.getDefault().register(this);
        coinImg = new HashMap<>();
        coinImg.put("BTC", R.mipmap.bibi_icon_btc);
        coinImg.put("BCH", R.mipmap.bibi_icon_bch);
        coinImg.put("ETC", R.mipmap.bibi_icon_etc);
        coinImg.put("ETH", R.mipmap.bibi_icon_eth);
        coinImg.put("LTC", R.mipmap.bibi_icon_ltc);
        coinImg.put("EOS", R.mipmap.bibi_icon_eos);
        coinImg.put("DASH", R.mipmap.bibi_icon_dash);
        coinImg.put("ZEC", R.mipmap.bibi_icon_zec);
        coinImg.put("XRP", R.mipmap.bibi_icon_xrp);
        coinImg.put(null, R.mipmap.eth_null);
        coolRefreshView.setPullHeader(new MaterialHeader(getActivity()));
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
//        recyclerView.addItemDecoration(new DividerLineItemDecoration(getActivity())
//                .setFirstDraw(false)
//                .setDividerColor(getResources().getColor(R.color.bibi_525))
//        );

        initAdapter();
    }


    private void initAdapter() {
        slimAdapter = SlimAdapter.create().register(R.layout.bibi_recy_item_slide, new SlimInjector<CoinBean>() {
            @Override
            public void onInject(CoinBean stock, IViewInjector injector, List<Object> payloads) {
                injector
                        .text(R.id.tvType, stock.getCode().toUpperCase().replace("_", "/").split("/")[0])
                        .text(R.id.tvPrice, stock.getPrice())
                        .text(R.id.tvTypeRight, "/" + stock.getCode().toUpperCase().replace("_", "/").split("/")[1])
                        .textColor(R.id.tvPrice, ContextCompat.getColor(App.INSTANCE, stock.isUp() ? R.color.bibi_03c : R.color.bibi_e76));
//                if (payloads == null || payloads.size() == 0) {
////                    injector.image(R.id.ivCoin, coinImg.get(stock.getCode().split("/")[0]) != null ? coinImg.get(stock.getCode().split("/")[0]) : coinImg.get(null));
//                    if (coinImg.get(stock.getCode().split("/")[0]) != null) {
//                        injector.image(R.id.ivCoin, coinImg.get(stock.getCode().split("/")[0]));
//                    }
//                }
//                double change = 0;
//                try {
//                    change = Double.valueOf(stock.getChange());
//                } catch (NumberFormatException e) {
//                    e.printStackTrace();
//                }
//                injector.text(R.id.tvPrice, stock.getPrice())
//                        .text(R.id.tvType, stock.getCode().split("/")[0])
//                        .text(R.id.tvVolume, App.INSTANCE.getString(R.string.bibi_slideHangqingFragment1_j) + stock.getVolume())
//                        .text(R.id.tvRMBPrice, "≈ ￥ " + stock.getCnyPrice())
//                        .background(R.id.tvRate, change >= 0 ?
//                                R.drawable.bibi_shape_green : R.drawable.bibi_shape_red)
//                        .text(R.id.tvRate, stock.getChangeRate())
//                        .textColor(R.id.tvPrice, stock.isLight() ?
//                                (getResources().getColor(stock.isGreen() ? R.color.bibiGreenText : R.color.bibiRedText)) :
//                                (change >= 0 ? getResources().getColor(R.color.bibiGreenText) : getResources().getColor(R.color.bibiRedText)));
////                        .textColor(R.id.tvPrice, stock.isLight() ?
////                                (getResources().getColor(stock.isGreen() ? R.color.bibiGreenText : R.color.bibiRedText)) :
////                                getResources().getColor(R.color.commonWhite));
            }
        }).attachTo(recyclerView).updateData(new ArrayList());
        ItemClickSupport.addTo(recyclerView)
                .setOnItemClickListener((recyclerView, position, v) -> {
                    RxBus.getDefault().post(new BibiCoinType(slimAdapter.getData().get(position).getCode(), qu));
                    getActivity().finish();
                });
        RefreshDataSource<CoinBean> refreshDataSource = new RefreshDataSource<CoinBean>() {
            @Override
            public Flowable<List<CoinBean>> loadData() {
                return mPresenter.getProduct(qu, null);
            }
        };
        mvcHelper = new MVCCoolHelper<>(coolRefreshView);
        mvcHelper.setDataSource(refreshDataSource);
        mvcHelper.setAdapter(slimAdapter);
        mvcHelper.refresh();
    }

    @Override
    public void onDestroy() {
        RxBus.getDefault().unregister(this);
        super.onDestroy();
    }
}
